<template>
  <div v-if="!noData" class="padding-20 page-box-row-left function-manage">
    <FormBlock :title="$t('module.function.functionInfo')" direction="column" style="width: 25%;">
      <el-tree
        :data="baseData"
        :props="defaultProps"
        highlight-current
        check-strictly
        :indent="10"
        node-key="functionId"
        ref="functionTree"
        icon-class="ivu-icon-ios-arrow-forward"
        @node-click="handleNodeClick"
        :render-content="renderContent"
        :expand-on-click-node="false"
      ></el-tree>
    </FormBlock>
    <FormBlock :title="functionTitle" direction="column">
      <Button
        slot="tool-bar"
        icon="md-create"
        type="primary"
        class="ivu-btn-hr btn-position"
        v-show="isShowResource || isShowEdit"
        @click="modifyFunction"
      >{{ this.$t('module.function.editfunction') }}</Button>
      <div v-if="isShowResource">
        <!-- 资源管理 -->
        <menu-resource-manage
          :functionData="functionData"
          :applicationList="applicationList"
          :key="functionData.functionCode"
        ></menu-resource-manage>
      </div>
      <div v-else>
        <div v-if="showDetail && this.baseData && this.baseData.length > 0">
          <div v-if="isRoot">
            <Form
              ref="functionForm"
              :model="productMessage"
              label-position="right"
              :label-width="100"
            >
              <Row :gutter="20" class="code-row-bg">
                <Col span="20">
                  <Form-item prop="functionCode" :label="$t('module.function.applicationCode')">
                    <Input v-model.trim="productMessage.code" disabled></Input>
                  </Form-item>
                </Col>
              </Row>
              <Row :gutter="20" class="code-row-bg">
                <Col span="20">
                  <Form-item prop="functionName" :label="$t('module.function.applicationName')">
                    <Input v-model.trim="productMessage.name" disabled></Input>
                  </Form-item>
                </Col>
              </Row>
            </Form>
          </div>
          <div v-else>
            <!-- 编辑功能  组件 -->
            <new-edit-function
              v-if="!isAdd"
              ref="newEditFunction"
              :applicationList="applicationList"
              :functionForm="functionForm"
              :key="functionForm.functionName + functionForm.functionId"
              @newEditFuntionSave="newEditFuntionSave"
              @newEditFuntionCancel="newEditFuntionCancel"
            ></new-edit-function>

            <!-- 添加功能  组件 -->
            <new-add-function
              v-else
              :applicationList="applicationList"
              :newAddProps="newAddProps"
              :key="newAddProps.functionModuleId + newAddProps.parentFunctionName"
              @newAddFuntionSave="newAddFuntionSave"
              @newAddFuntionCancel="newAddFuntionCancel"
            ></new-add-function>
          </div>
        </div>
        <!-- 暂无数据 -->
        <div v-else class="noInfoShow">{{ $t("module.function.noData") }}</div>
      </div>
    </FormBlock>
  </div>
  <div class="sidelip-noInfor" v-else style=" text-align: center;margin-top: 100px;"></div>
</template>
<script>
import Three from "@/tools/getThree.js";
import newAddFunction from "./newAddFunction.vue";
import newEditFunction from "./newEditFunction.vue";
import MenuResourceManage from "./resourceManage/MenuResourceManage";
import EditFunction from "./EditFunction.vue";
import { searchAppList } from "@/api/applicationApi.js";
import { queryResouceList } from "@/api/resourceApi.js";
import functionAPI from "@/api/functionAPI.js";
import { CoreModuleName } from "@/const.js";
import locales from "./locales.js";

export default {
  name: "function-manage",
  title: "this.$t('module.function.manageFunction')",
  mixins: [locales],
  components: {
    MenuResourceManage,
    newAddFunction,
    newEditFunction
  },
  data() {
    return {
      tenantCode: "",
      baseData: [],
      productMessage: {
        // 应用信息
        code: "",
        name: ""
      },
      defaultProps: {
        children: "children",
        label: "functionName"
      },
      level: 1, //树结构的层级 1代表最顶级
      isRoot: true, //树结构  当前是否为最顶级
      noData: false, //是否有数据
      showDetail: true, //是否显示功能和功能目录
      isAdd: false, //是否点击添加
      isShowResource: false, //是否显示资源管理
      isShowEdit: false, //是否显示编辑按钮
      functionData: {}, //功能信息 (传递到MenuResourceManage.vue)
      newAddProps: {
        //功能目录信息 (传递到newAddFunction.vue)
        parentFunctionName: "",
        functionModuleId: "",
        applicationId: ""
      },
      functionTitle: "",
      saveLoading: false,
      functionForm: {
        functionCode: "",
        functionName: "",
        functionId: "",
        enabled: 1,
        parentFunctionName: "",
        functionModuleId: "", //parentfunctionId
        functionDesc: "",
        sort: "",
        actionUrl: "",
        functionType: "",
        applicationId: "",
        functionLangs: []
      },
      node: {},
      applicationList: {}
    };
  },
  computed: {},
  created: function() {
    this.getNowTenantCode();
    this.QueryApplication();
  },
  mounted: function() {
    this.selectFirstFunction(); //加载时默认显示页
  },
  methods: {
    newEditFuntionSave(value) {
      this.QueryApplication();
      this.$message.success({
        content: this.$t("module.function.modifySuccess"),
        duration: 3
      });
      this.saveLoading = false;
      this.isAdd = false;
      this.isRoot = true;
      this.isShowEdit = false;
    },
    newEditFuntionCancel() {},
    newAddFuntionSave(value) {
      this.QueryApplication();
      this.$message.success({
        content: this.$t("common.addSuccess"),
        duration: 3
      });
      this.isAdd = false;
      this.isRoot = true;
    },
    newAddFuntionCancel() {
      if (this.functionForm.functionCode == "") {
        this.functionForm = this.copyFunctionForm;
      }
      if (this.level > 1) {
        if (this.functionForm.functionCode == "") {
          this.isRoot = true;
        } else {
          this.isRoot = false;
          this.isShowEdit = true;
        }
      } else {
        this.isShowEdit = false;
        this.isRoot = true;
      }
      if (this.isAdd) {
        this.isAdd = false;
      }
    },
    // 获取应用
    QueryApplication() {
      this.baseData = [];
      searchAppList({ pageNum: 1, pageSize: 200 })
        .then(({ data: { records } }) => {
          this.applicationList = {};
          records.forEach(application => {
            this.applicationList[application.clientId] = application.appName;
            // 授权应用不显示，自建应用显示，deleteAppFlag == 0为授权应用
            let temp = {};
            if (this.tenantCode == application.tenantCode) {
              temp = {
                id: "0",
                functionName: application.appName,
                functionId: application.id,
                functionCode: application.clientId,
                applicationId: application.clientId,
                functionDesc: this.$t("module.function.topFunction"),
                parentFunctionName: this.$t("module.function.nothing"),
                sort: 0,
                actionUrl: this.$t("module.function.nothing"),
                functionType: "1",
                isRootNode: true,
                children: [] //后天调取的树中的data放在这里
              };
              this.baseData.push(temp);
            }
            this.loadNode(application.clientId, temp);
          });
          this.$nextTick(() => {
            //初始化加载
            this.functionTitle = this.baseData[0].functionName;
            this.productMessage.code = this.baseData[0].functionCode;
            this.productMessage.name = this.baseData[0].functionName;
          });
        })
        .catch(error => {
          this.$message.error({
            content: error.message,
            duration: 3
          });
        });
    },

    //添加删除小图标
    renderContent(h, { node, data, store }) {
      return (
        <span class="node-items">
          <icon
            v-show={data.functionType == "0"}
            type={data.iconCls || "md-apps"}
            class="icon-size icon-margin-right"
          />
          <icon
            v-show={data.functionType != "0"}
            type={data.iconCls || "md-menu"}
            class="icon-size icon-margin-right"
          />
          <span class="node-label" title={node.label}>{node.label}</span>
          <div class="orgEditMenu" id={"MENU" + data.functionId}>
            <span
              // v-show={data.functionType != "0"} //条件过滤显示
              style={data.functionType != "0" ? "" : "visibility: hidden;" }
              class="orgEditSonMenu"
              on-click={event => this.addFunction(false, node, event)} //传入event解决火狐兼容性问题
            >
              {/* <i class="el-icon-plus" title={this.$t("module.function.create")}>
                {" "}
              </i> */}
              <Icon type="md-add"></Icon>
            </span>
            <span
              // v-show={data.isRootNode != true} //条件过滤显示
              style={data.isRootNode != true ? "" : "visibility: hidden;" }
              class="orgEditSonMenu"
              on-click={event => this.deleteFunction(data, node, event)}
            >
              {/* <i class="el-icon-delete" title={this.$t("module.function.delete")}>
                {" "}
              </i> */}
              <Icon type="ios-trash"></Icon>
            </span>
          </div>
        </span>
      );
    },
    remove(store, data) {
      store.remove(data);
    },
    // 点击树节点
    handleNodeClick(data, node, nodeElement) {
      functionAPI.getLang(data.id).then(res => {
        this.functionForm.functionLangs = [];
        let result = res;
        this.functionForm = {
          functionLangs: result,
          functionId: data.id,
          functionCode: data.functionCode,
          functionName: data.functionName,
          functionDesc: data.functionDesc,
          iconCls: data.iconCls,
          enabled: data.enabled,
          functionType: data.functionType,
          functionModuleId: data.functionModuleId,
          sort: data.sort,
          actionUrl: data.actionUrl,
          parentFunctionName: node.parent.data.functionName,
          isShowProduct: data.isShowProduct,
          applicationId: data.applicationId
        };
        this.isAdd = false;
        this.functionTitle = data.functionName;
        // 如果选择功能则显示资源管理  否则显示应用详情或者应用目录
        if (data.functionType == "0") {
          this.isShowResource = true;
          this.functionData = data;
        } else {
          this.isShowResource = false;
        }
        this.level = node.level;
        if (data.isRootNode) {
          this.isShowEdit = false;
          this.isRoot = true;
          this.productMessage.name = data.functionName;
          this.productMessage.code = data.functionCode;
        } else {
          this.isRoot = false;
          this.isShowEdit = true;
        }

        this.node = node;

        this.showDetail = true;
        let v_parentFunctionName = node.parent.data.functionName;
      });
    },
    // 点击添加按钮
    addFunction(addTopFunction, node, event) {
      this.isAdd = false;
      this.$nextTick(() => {
        if (addTopFunction || this.node == null) {
          this.noData = false;
        } else {
          this.newAddProps.parentFunctionName = node.data.functionName;
          this.newAddProps.functionModuleId = node.data.id == "0" ? "" : node.data.functionId;
          if (!!node.data.isRootNode) {
            this.newAddProps.applicationId = node.data.functionCode;
          } else {
            this.newAddProps.applicationId = node.data.applicationId;
          }
        }
        this.isAdd = true;
      });
      functionAPI.getLang(node.data.functionId).then(res => {
        this.functionForm.functionLangs = [];
        let result = res;
        this.functionForm = {
          functionLangs: result,
          functionId: node.data.id,
          functionCode: node.data.functionCode,
          functionName: node.data.functionName,
          functionDesc: node.data.functionDesc,
          iconCls: node.data.iconCls,
          enabled: node.data.enabled,
          functionType: node.data.functionType,
          functionModuleId: node.data.functionModuleId,
          sort: node.data.sort,
          actionUrl: node.data.actionUrl,
          parentFunctionName: node.parent.data.functionName,
          isShowProduct: node.data.isShowProduct,
          applicationId: node.data.applicationId
        };
      });
      if (node.level == "1") {
        this.productMessage.name = node.data.functionName;
        this.productMessage.code = node.data.functionCode;
      }
      this.functionTitle = node.data.functionName;

      this.isAdd = true;
      this.level = node.level;
      this.isShowEdit = false;
      this.isRoot = false;
      this.isShowResource = false;
      // 选中当前节点
      this.$refs["functionTree"].setCurrentKey(node.data.functionId);
      // node.data.functionId;
      event.stopPropagation(); //阻止点击事件向上冒泡
      // this.functionTitle = this.$t("module.function.addfunction");
      let parentFunctionName = "";
      let parentId = "";
      let applicationId = "";
      this.node = node;
      this.showDetail = true;
    },
    processFunctionId(data) {
      for (let item of data) {
        item.functionId = item.id;
        if (!!item.children) {
          this.processFunctionId(item.children);
        }
      }
    },
    loadNode(appId, rootNodeData) {
      functionAPI.queryFunctionList(appId).then(data => {
        // 改为递归遍历
        this.processFunctionId(data);
        let tree = new Three(data, {
          sort: true
        });
        //遍历baseData 根据应用类型
        rootNodeData.children = data;
      });
    },
    // 删除树节点
    deleteFunction(data, node, event) {
      //有效树节点不能删除
      if (data.enabled == 1) {
        this.$message.error({
          content: this.$t("module.function.warning.canNotDelEnabled"),
          duration: 3
        });
        return;
      }
      //有子节点不能删除
      if (data.children && data.children.length > 0) {
        this.$message.error({
          content: this.$t("module.function.warning.cannotDelNode"),
          duration: 3
        });
        return;
      }
      // 功能下存在资源,删除给出严重警告，没有一般警告
      if (data.functionType == "0") {
        let param = {
          condition: {
            applicationId: data.applicationId,
            functionId: data.functionId
          }
        };
        queryResouceList(param).then(res => {
          if (res.total == 0) {
            event.stopPropagation(); //火狐不支持
            let parentNode = node.parent;
            new $confirm(this.$t("module.function.confirmDelete"), this)
              .then(() => {
                this.delete(data, node, parentNode);
              })
              .catch(_ => _);
          } else {
            event.stopPropagation(); //火狐不支持
            let parentNode = node.parent;
            this.$confirm
              .swarning(this.$t("module.function.warning.deleteAllResource"))
              .then(() => {
                this.delete(data, node, parentNode);
              })
              .catch(_ => _);
          }
        });
      } else {
        event.stopPropagation(); //火狐不支持
        let parentNode = node.parent;
        new $confirm(this.$t("module.function.confirmDelete"), this)
          .then(() => {
            this.delete(data, node, parentNode);
          })
          .catch(_ => _);
      }
    },
    // 删除功能
    delete(data, node, parentNode) {
      functionAPI.deleteFunction([data.functionId]).then(data => {
        this.$message.success({
          content: this.$t("module.function.deleteSuccess"),
          duration: 3
        });
        //此处应该刷新功能树,右侧显示上级功能
        this.remove(node.store, node.data);
        if (parentNode.level > 0) {
          this.$refs["functionTree"].setCurrentKey(parentNode.data.functionId);
          this.handleNodeClick(parentNode.data, parentNode);
        } else {
          this.baseData = [];
          this.noData = true;
        }
      });
    },
    // 编辑功能
    modifyFunction() {
      if (this.isShowResource) {
        new this.$pageModal(
          EditFunction,
          {
            props: {
              applicationList: this.applicationList,
              functionForm: this.functionForm
            }
          },
          data => {
            if (!!data) {
              let paramEdit = {
                id: data.functionId,
                applicationId: data.applicationId,
                functionCode: data.functionCode,
                functionName: data.functionName,
                functionDesc: data.functionDesc,
                enabled: data.enabled,
                iconCls: data.iconCls,
                functionType: data.functionType,
                actionUrl: data.actionUrl,
                functionModuleId: data.functionModuleId,
                sort: data.sort,
                functionLangs: data.functionLangs
              };
              functionAPI
                .updateFunction(paramEdit)
                .then(data => {
                  this.QueryApplication();
                  this.$message.success({
                    content: this.$t("module.function.modifySuccess"),
                    duration: 3
                  });
                  this.saveLoading = false;
                  this.isShowResource = false;
                  this.isRoot = true;
                })
                .catch(error => {
                  this.saveLoading = false;
                });
            }
          }
        );
      } else {
        this.$refs["newEditFunction"].editFunction();
        this.isAdd = false;
      }
    },
    // 默认显示第一个功能信息
    selectFirstFunction() {
      if (this.baseData && this.baseData.length > 0) {
        this.$refs["functionTree"].setCurrentKey(this.baseData[0].functionId);
        this.showDetail = true;
        this.functionForm = {
          functionCode: this.baseData[0].functionCode,
          functionName: this.baseData[0].functionName,
          functionDesc: this.baseData[0].functionDesc,
          functionType: this.baseData[0].functionType,
          sort: this.baseData[0].sort,
          iconCls: "",
          parentenuName: "",
          parentId: this.baseData[0].parentId
        };
      }
    },
    // 查询租户编码
    getNowTenantCode() {
      this.userInfo = $store.state["ripples-components"].userInfo;
      if (!this.userInfo) return;
      // 根据当前角色查询租户编码
      this.tenantCode = this.userInfo.tenantCode;
    }
  }
};
</script>
<style lang="less">
.function-manage {
  .noInfoShow {
    display: block;
    text-align: center;
    margin: 5% 0;
  }
  .ivu-form + .noInfoShow {
    display: none;
  }
  .icon-margin-right {
    margin-right: 5px;
  }
  .icon-select {
    width: 20px;
    height: 20px;
    background-size: cover;
    display: inline-block;
    position: absolute;
    font-size: 20px;
    right: 6px;
    top: 7px;
    cursor: pointer;
  }

  .icon-size {
    font-size: 12px;
  }
  .form-block-title {
    display: flex;
    flex-basis: row;
    justify-content: space-between;
    align-items: center;
    .btn-position {
      margin-right: 20px;
    }
  }
  .node-label {
    // width: calc(~"100% - 86px");
    // display: inline-block;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  // .form-block{
  //   .ivu-form{
  //     overflow: hidden;
  //   }
  // }
}

//这个已转移到组件工程解决
</style>
